import asyncio
import time
from datetime import datetime
import websockets
import paho.mqtt.client as mqtt
from pubAndSub.subscribeV2 import connect_mqtt, sub

# 全局变量用于存储 MQTT 消息的时间戳
mqtt_message_time = None

# 记录时间戳的函数
def get_timestamp_milliseconds():
    return int(time.time() * 1000)

# MQTT 处理消息的回调
def on_message(client, userdata, msg):
    global mqtt_message_time
    payload = msg.payload.decode()
    if '湘A1A80W' in payload:
        mqtt_message_time = get_timestamp_milliseconds()  # 记录收到 MQTT 消息的时间戳
        print(f"[{mqtt_message_time}] Received MQTT message on topic '{msg.topic}': {payload}")

# MQTT 客户端连接和订阅
def start_mqtt(topics, filter_string):
    client = connect_mqtt()
    sub(client, topics, filter_string)
    client.on_message = on_message
    client.loop_start()  # 使用 loop_start 以便在后台线程中运行

# WebSocket 客户端函数
async def websocket_client(url, payload=None):
    try:
        async with websockets.connect(url) as websocket:
            print(f"WebSocket connected to {url}")

            if payload:
                # 发送消息
                await websocket.send(payload)
                print(f"Message '{payload}' sent successfully.")

            while True:
                message = await websocket.recv()
                receive_time = get_timestamp_milliseconds()  # 记录 WebSocket 收到消息的时间戳

                if mqtt_message_time is not None:
                    time_diff = receive_time - mqtt_message_time  # 计算时间差
                    print(f"Time difference between MQTT and WebSocket messages: {time_diff} ms")
                else:
                    print("MQTT message timestamp not set yet.")

                print(f"Received WebSocket message: {message}")

    except websockets.exceptions.ConnectionClosedOK:
        print("WebSocket connection closed gracefully.")
    except Exception as e:
        print(f"WebSocket connection or communication error: {e}")

# 主函数
async def main():
    url = 'ws://192.168.101.202/gateway/tw-tunnel-server/websocket/globalTrack&drivingTrajectory&super_admin?tokenauthorization=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiI0Yjk1NmVlMjM1ZmI0NzJkOTllMmQ4M2FiZTc0YmIzZiIsImF1ZCI6ImlvYyIsImlzcyI6Im9hdXRoIiwicm5kIjoiejAzMHUwOHMiLCJleHAiOjM4NTk2MDg4MjEsImlhdCI6MTcxMjEyNTE3NH0.6waBppaLAnYWnb0PBzxcHqxBmfK4t1mBANgOGATJ3o4&tenantid=T1000'
    # 启动 MQTT 客户端
    filter_string = "湘A1A99W"  # 需要过滤payload的数据
    topics = [{"subscribe": "bizdata/objects_list"}]
    start_mqtt(topics, filter_string)
    # 启动 WebSocket 客户端
    await websocket_client(url)

if __name__ == "__main__":
    asyncio.run(main())